<template>
  <!-- 批量上传 -->

  <div>
    <el-dialog
      title="批量上传"
      :visible.sync="dialogVisible"
      width="40%"
      :close-on-click-modal="false"
      destroy-on-close
      :before-close="handleClose"
    >
      <el-form :model="infoModel" :rules="rules" ref="dynamicValidateForm" label-width="150px" class="demo-dynamic">
        <el-row>
          <el-col :span="24">
            <el-form-item prop="email" label="信息模板：">
              <el-button
                ghost
                type="primary"
                icon="el-icon-download"
                :loading="isDowLoding"
                :disabled="isDowLoding"
                @click="downloadMethod()"
                >&ensp;点击下载</el-button
              >
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item prop="fileList" label="批量上传：">
              <el-upload
                class="upload-demo"
                action=""
                accept=".xlsx,.xls"
                ref="upload"
                :before-upload="uploadHandler"
                :before-remove="handleRemove"
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="infoModel.fileList"
              >
                <el-button size="small" icon="el-icon-upload2" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip" style="color:#a8a8a8;">只能上传xlsx/xls文件，且不超过50M</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" :loading="save_loading" :disabled="save_loading" @click="save">确 定 上 传</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import { dowloadFileResFunction } from '@/libs/common.js'
import config from '@/libs/config.js'
import API from '@/api/product.js'

export default {
  name: 'uploadInfo',
  props: {
    showModal: {
      type: Boolean,
      default: () => false,
    },
  },

  watch: {
    showModal: {
      handler(val) {
        this.dialogVisible = val
      },
      deep: true,
    },
  },

  data() {
    return {
      rules: {
        fileList: [
          {
            required: true,
            trigger: 'change',
            msgName: '请选择上传的文件',
            validator: (rule, value, callback) => {
              value = this.infoModel.fileList
              console.log(this.fileSize, 'this.fileSize')
              if (!value || !value.length) {
                callback(new Error(rule.msgName))
              } else if (this.fileSize) {
                this.$nextTick(() => {
                  this.$refs.upload.clearFiles()
                })
                callback(new Error('上传文件不超过50M'))
              } else {
                callback()
              }
            },
          },
        ],
      },
      save_loading: false,
      fileSize: false,
      infoModel: { fileList: [] },
      isDowLoding: false,
      dialogVisible: this.showModal,
    }
  },

  methods: {
    downloadMethod() {
      window.open(`${config.url}/template/productExecls.xlsx`)
    },

    save() {
      this.$refs.dynamicValidateForm.validate(async valid => {
        if (valid) {
          try {
            const fromData = new FormData()
            fromData.append('file', this.infoModel.fileList[0])
            this.save_loading = true

            const RES = await API.productBatchUpload(fromData)

            console.log(RES, '========')
            this.save_loading = false
            if (RES.code == 200) {
              this.$message({
                message: '批量上传成功',
                type: 'success',
              })
              this.handleClose()
            }
          } catch (error) {
            this.save_loading = false
          }
        }
      })
    },

    handleRemove(file) {
      if (file.status == 'success') {
        this.$confirm(`确定移除 ${file.name}`, '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(async () => {
          this.infoModel.fileList = []
        })
      }
      return false
    },

    uploadHandler(file) {
      this.infoModel.fileList = [file]

      // 上传文件不大于 50M
      if (file.size / 1024 / 1024 > 50) {
        this.fileSize = true
      } else {
        this.fileSize = false
      }
      this.$refs.dynamicValidateForm.validateField('fileList')

      return false
    },

    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`,
      )
    },

    handleClose() {
      this.save_loading = false
      this.dialogVisible = false
      this.infoModel = { fileList: [] }
      this.$refs.upload.clearFiles()
      this.$refs.dynamicValidateForm.resetFields()
      this.$emit('get-data')
      this.$emit('update:showModal', this.dialogVisible)
    },
  },
}
</script>
